var domainName = document.location.href.substring(0, document.location.href.indexOf("/", document.location.href.indexOf("/", 7) + 1));

var pageload = function() {
    try {
        var notifs = document.querySelectorAll("#notifications.zero span, .task-new.zero span");
        for (i = 0; i < notifs.length; i++) {
            var notif = notifs[i];
            if (notif.innerHTML !== "0")
            {
                notif.parentNode.className = notif.parentNode.className.replace(/ zero/, "");
            } else {
                notif.parentNode.className += " zero";
            }
        }
    } catch (e) {
    }
};

var htmlready = function() {
    //Add task detail page link
    var tasks = document.querySelectorAll("ul.task-list li");
    for (var elementIterator = 0; elementIterator < tasks.length; elementIterator++) {
        tasks[elementIterator].addEventListener("click", taskDetails, false);
    }

    //Add messages collapse/expand option
    var messages = document.querySelectorAll(".task-details-page .message");
    for (var elementIterator = 0; elementIterator < messages.length; elementIterator++) {
        messages[elementIterator].addEventListener("click", inverseMessageDisplayStatus, false);
    }

    //Add a keyup listener to automaticaly refresh the targeted elements list
    var filterInput = document.getElementById("filter");
    if (filterInput !== null) {
        filterInput.addEventListener("keyup", filterElements, false);
    }

    //Display ui-messages
    displayUIMessage();

    //Setup the header task list shortcut
    try {
        document.getElementById("task-shortcut").addEventListener("change", taskShorcutListener, false);
    } catch (e) {
    }

    //Improve UI
    var checks = document.querySelectorAll(".select-checkbox tr")
    for (var i = 0; i < checks.length; i++) {
        checks[i].addEventListener("click", invertInnerCheckbox, false);
    }

    //hack
    var inputsToCheck = document.querySelectorAll('input[data-onload="checked"]');
    for (var i = 0; i < inputsToCheck.length; i++) {
        inputsToCheck[i].setAttribute("checked", "checked");
    }
};
var taskDetails = function() {
    try {
        redirectToTask(this.getElementsByTagName("input")[0].value);
    } catch (ex) {
        console.log("Warning: cannot retreive task id (The hidden input that is supposed to store the value is missing)");
        console.log(ex);
    }
};
var redirectToTask = function(id) {
    window.location.href = domainName + "/faces/user/task.xhtml?id=" + id;
}
var inverseMessageDisplayStatus = function() {
    if (this.className.indexOf("expand") === -1) {
        this.className += " expand";
    } else {
        this.className = this.className.replace(/ expand/, "");
    }
};
var getParamValue = function(param) {
    var paramIndex = window.location.search.indexOf(param) + param.length + 1;
    var paramEndIndex = window.location.search.indexOf("&", paramIndex);
    if (paramEndIndex === -1) {
        paramEndIndex = window.location.search.length;
    }
    if (paramIndex === param.length)
        return "";
    else
        return decodeURIComponent(window.location.search.substring(paramIndex, paramEndIndex));
};
var filterElements = function() {
    var value = this.value.toLowerCase();
    var targetContainer = document.getElementById("filter-target");
    var dataTarget = targetContainer.getAttribute("data-target");
    var dataElement = targetContainer.getAttribute("data-element");
    var elements = targetContainer.querySelectorAll(dataElement);
    for (var elementIterator = 0; elementIterator < elements.length; elementIterator++) {
        var currentElement = elements[elementIterator];
        if (value !== "") {
            currentElement.style.display = "none";
            var toCheck = currentElement.querySelectorAll(dataTarget);
            var words = value.split(" ");
            var foundCount = 0;
            for (var nthWord = 0; nthWord < words.length; nthWord++) {
                var word = words[nthWord];
                var found = false;
                var checkIterator = 0;
                while (!found && checkIterator < toCheck.length) {
                    if (toCheck[checkIterator++].innerHTML.toLowerCase().indexOf(word) !== -1) {
                        found = true;
                    }
                }
                if (found) {
                    foundCount++;
                }
            }
            if (foundCount === words.length) {
                currentElement.style.display = "block";
            }
        } else {
            currentElement.style.display = "block";
        }
    }
};
var displayUIMessage = function() {
    var messageContainer = document.getElementById("ui-message");
    var messageValue = getParamValue("ui-message");
    var messageDuration = getParamValue("ui-message-duration");
    if (messageValue != "") {
        try {
            messageDuration = parseInt(messageDuration !== "" ? messageDuration : "10000");
        } catch (e) {
            messageDuration = 10000;
        }
        messageContainer.innerHTML = messageValue;
        messageContainer.className = "display";
        setTimeout(function() {
            messageContainer.className = "";
        }, messageDuration);
    }
};
var taskShorcutListener = function() {
    redirectToTask(this.options[this.selectedIndex].value);
};
var invertInnerCheckbox = function() {
    this.querySelector("input").checked = !this.querySelector("input").checked;
};

window.addEventListener("load", pageload, false);
window.addEventListener("DOMContentLoaded", htmlready, false);
